#include "Connection.h"


Connection::Connection()
{
	connected = false;
	changeSet = 0;
}


Connection::~Connection(void)
{
	if(changeSet != 0)
		free(changeSet);
}


int Connection::connect(){
	open = InternetOpen(TEXT(USER_AGENT), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL);
	if(open == 0)
		return 1;
	session = InternetConnect(open, TEXT(SERVER), INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, NULL, NULL);
	if(session == 0){
		InternetCloseHandle(open);
		return 2;
	}
	LPCSTR accept[] = {ACCEPT_TYPE_TEXT, NULL};
	query = HttpOpenRequest(session, POST, SERVER_DIR, NULL, NULL, accept, NULL, NULL);
	if(query == NULL){
		InternetCloseHandle(session);
		InternetCloseHandle(open);
		return 3;
	}
	connected = true;
	return 0;
}


int Connection::loadFile(char *path){
	DWORD state;
	char in;
	if(!connected || path == 0)
		return 1;
	std::ofstream out(path, std::ios::out | std::ios::binary);
	while(InternetReadFile(query, &in, 1, &state)){
		if(state != 1)
			break;
		out.write(&in, 1);
	}
	out.close();
	close();
	return 0;
}


int Connection::requestFile(char *path, char *file){
	char load[256];
	char in;
	DWORD state;
	open = InternetOpen(TEXT(USER_AGENT), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL);
	if(open == 0)
		return 1;
	session = InternetConnect(open, TEXT(SERVER), INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, NULL, NULL);
	if(session == 0){
		InternetCloseHandle(open);
		return 2;
	}
	LPCSTR accept[] = {ACCEPT_TYPE_TEXT, NULL};
	sprintf_s(load, 256, "%s%s", path, file);
	query = HttpOpenRequest(session, GET, load, NULL, NULL, accept, NULL, NULL);
	if(query == NULL){
		InternetCloseHandle(session);
		InternetCloseHandle(open);
		return 3;
	}
	HttpSendRequest(query, NULL, NULL, NULL, NULL);
	connected = true;
	return 0;
}


int Connection::sendRequest(char *data){
	char aHeader[256];
	int result;
	if(!connected)
		return 1;
	sprintf_s(aHeader, 256, "%s%d\r\n", ADDITIONAL_HEADER, strlen(data));
	result = HttpSendRequest(query, aHeader, strlen(aHeader), data, strlen(data));
	if(result == FALSE)
		return 2;
	return 0;
}


char* Connection::receive(){
	char in, *result, *buffer;
	DWORD state;
	int pos;
	result = (char*)malloc(1);
	pos = 0;
	while(InternetReadFile(query, &in, 1, &state)){
		if(state != 1)
			break;
		result[pos] = in;
		pos++;
		buffer = (char*)malloc(pos+1);
		memcpy(buffer, result, pos);
		free(result);
		result = buffer;
	}
	result[pos] = '\0';
	return result;
}